package io.gitee.yxsnake.embark.web.core.interceptor;

import io.gitee.yxsnake.embark.web.core.constant.Commons;
import io.gitee.yxsnake.embark.web.core.context.UserContext;
import io.gitee.yxsnake.embark.web.core.context.model.UserInfoDTO;
import io.gitee.yxsnake.embark.web.core.utils.JsonUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import java.net.URLDecoder;

/**
 * @author: snake
 * @create-time: 2024-09-30
 * @description:
 * @version: 1.0
 */
@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userContext = request.getHeader(Commons.USER_CONTEXT);
        if(StrUtil.isNotBlank(userContext)){
            UserInfoDTO userInfoDTO = JsonUtils.jsonCovertToObject(URLDecoder.decode(userContext,"UTF-8"), UserInfoDTO.class);
            UserContext.setContext(userInfoDTO);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear();
    }
}
